<script setup lang="ts">
// -- imports
import {onMounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {api} from "@/api/apiServer";
import msgIco from '@/assets/images/message.png';
import kq_ico from '@/assets/images/kq_ico.png';
import OrderLog from "comps/orderLog.vue";
import Tools from "@likg/tools";
import {aes_encrypt} from "@/utils/aes_endecrypt";
import {getSyncEnergy} from "@/api/apiServer/api.ts";

const env = Tools.getEnv();
const router = useRouter();
const route = useRoute();
const channelId = route.query.channelId || localStorage.getItem("channelId");

interface StateProps {
    isRefreshing: boolean;
    page: number,
    data: any[] | null,
    isLoading: boolean,
    isFinished: boolean,
    type: string,
}

// -- state
const state = reactive<StateProps>({
    isRefreshing: false,
    page: 1,
    data: null,
    isLoading: false,
    isFinished: false,
    type: "refresh",
});


let columns = [];
const fieldText = ref('');
const fieldValue = ref('');
const showPicker = ref(false);

const homeResData = ref({});
// 根据渠道id获取数据
const getHomeDataByChannelId = async () => {
    try {
        const resp = await api.getIndexDataByChannelId({
            channelId: localStorage.getItem("channelId") || channelId,
        });
        if (resp.code === 200) {
            homeResData.value = resp.data;
        }
    } catch (error) {
    }
}

const onConfirm = ({selectedOptions}) => {
    showPicker.value = false;
    fieldValue.value = selectedOptions[0].value;
    fieldText.value = selectedOptions[0].text;
    getHomeDataByChannelId();
};


const indexResData = ref<any>({});
const getIndexDataFn = async () => {
    let res = await api.getIndexData();
    if (res.code === 200) {
        indexResData.value = res.data;
    }
}

const getSyncEn = async () => {
    const res = await api.getSyncEnergy();
    if (res.code === 200) {
        homeResData.value.integralNumber = res.data;
    }
}

const onLoad = () => {
    state.page += 1;
    state.type = "load";
    getDataSource();
};


const getDataSource = async () => {
    try {
        const resp = await api.getUseRecord({
            pageNum: state.page,
            pageSize: 20,
        });
        const {current, total, records} = resp.data;
        // 处理数据
        if (state.type === "refresh" || state.data === null) {
            state.data = records;
            state.isRefreshing = false;
        } else {
            state.data = [...state.data!, ...records];
            state.isLoading = false;
        }
        state.isFinished = (state.data as any).length >= total;
    } catch (error) {
    }
};

// 跳转
const linkFn = (item: any) => {
    //路径拼接加密 拼接电话号码和sourceType=1&sourceType=2&phone=18600000000
    const param = {
        "phoneNumber": item.phoneNumber,
        "sourceType": 2,
        "channelId": localStorage.getItem("channelId") || channelId,
        "customerId": localStorage.getItem("customerId") || '',
        "salesmanId":'',
    }
    const newStr = aes_encrypt(JSON.stringify(param));
    //已经有参数的加& 否则加？
    if (item.appUrl.indexOf('?')>0) {
        window.location.href = item.appUrl?.concat('&param=').concat(encodeURIComponent(newStr));
    }  else {
        window.location.href = item.appUrl?.concat('?param=').concat(encodeURIComponent(newStr));
    }
}

// ==> events
const onRefresh = () => {
    getIndexDataFn();
    state.page = 1;
    state.type = "refresh";
    getDataSource();
};

// 跳转
const linkTo = (url: string) => {
    // 判断前缀是否有http,或https
    if (url.indexOf('http') === -1 && url.indexOf('https') === -1) {
        router.push(url);
    } else {
        window.location.href = url;
    }
}

//wxFn.checkToken();
// ==> life circles
onMounted(() => {
    getIndexDataFn();
    getDataSource()
    getHomeDataByChannelId();
});
</script>

<template>
    <div class="tab-page">
        <app-header v-if="env !== 'weixin'" title="日恒健康" :showBack="false" gradientColor="transparent"
                    :show-status-bar="false"/>
        <van-pull-refresh v-model="state.isRefreshing" @refresh="onRefresh">
            <div class="px-12">
                <!-- banner -->
                <div class="pt-10">
                    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
                        <van-swipe-item v-for="(item, index) in indexResData.banners" :key="index">
                            <img style="width: 100%;" :src="item.imageUrl" @click="linkTo(item.jumpLink)"/>
                        </van-swipe-item>
                    </van-swipe>
                </div>
                <!-- 公告 -->
                <div class="pt-13">
                    <van-notice-bar :left-icon="msgIco" style="border-radius: 16px; height:32px;" color="#F59F2F"
                                    background="rgba(245, 154, 35, .2)" :scrollable="false">
                        <van-swipe vertical class="notice-swipe" :autoplay="3000" :touchable="false"
                                   :show-indicators="false">
                            <van-swipe-item v-for="(item, index) in indexResData.notices" :key="index"
                                            @click="$router.push('/notice/details?noticeId=' + item.noticeId)">
                                {{ item.noticeTitle }}
                            </van-swipe-item>
                        </van-swipe>
                    </van-notice-bar>
                </div>
                <!-- 卡券信息 -->
                <!--         <div class="bg-FFFFFF rounded-8 my-10">-->
                <!--          <van-field-->
                <!--            v-model="fieldText"-->
                <!--            is-link-->
                <!--            readonly-->
                <!--            label="卡券信息"-->
                <!--            placeholder="请选择"-->
                <!--            @click="showPicker = true"-->
                <!--          />-->

                <!--         </div>-->
                <!-- 卡券 -->
                <div class="mt-10 myquanbox">
                    <div class="sign-in-item d-flex rounded-8">
                        <van-image width="46" height="46" :src="kq_ico"/>
                        <div class="ml-8">
                            <div class="f17 color-primary f-600">
                                <van-space>
                                    {{ homeResData.integralNumber || 0 }}J
                                    <van-icon  name="replay" @click="getSyncEn"/>
                                </van-space>
                            </div>
                            <div class="f13 mt-6 color-gary">活动能量</div>
                        </div>
                    </div>
                    <!--                    <div class="sign-in-item d-flex rounded-8" @click="$router.push('/kaquan/jingList')"-->
                    <!--                         v-if="homeResData.deductionStatus === 1">-->
                    <!--                        <van-image width="46" height="46" :src="dkj_ico"/>-->
                    <!--                        <div class="ml-8">-->
                    <!--                            <div class="f17 color-primary f-600">{{ homeResData.deductionAmount || 0 }}元</div>-->
                    <!--                            <div class="f13 mt-6 color-gary">抵扣金余额</div>-->
                    <!--                        </div>-->
                    <!--                    </div>-->
                </div>
                <!-- 菜单 -->
                <div class="menubox bg-FFFFFF rounded-8 mt-10" v-if="homeResData.apps && homeResData.apps.length > 0">
                    <div class="flex-v-center" v-for="(item, index) in homeResData.apps" :key="index"
                         @click="linkFn(item)">
                        <van-image width="54" height="54" :src="item.appLogo"/>
                        <div class="f12 color-2d mt-6">{{ item.name }}</div>
                    </div>
                </div>
            </div>
            <!-- 使用记录 -->
            <div class="pt-15 px-12 pb-21 bg-FFFFFF mt-10">
                <div class="title f16 lh-23 f-600 position-relative  border-bottom pb-18"
                     style="border-color: #97979720;">
                    <div class="position-relative zIndex-1">交易记录</div>
                </div>
                <van-list v-model:loading="state.isLoading" finished-text="" :finished="state.isFinished" :offset="50"
                          :immediate-check="false" @load="onLoad">
                    <template v-if="state.data && state.data.length > 0">
                        <OrderLog v-for="(item, index) in state.data" :key="index" :data="item"/>
                    </template>
                    <no-data tips="没有更多啦~" v-else/>
                </van-list>
            </div>
        </van-pull-refresh>


        <van-popup v-model:show="showPicker" round position="bottom">
            <van-picker
                :columns="columns"
                @cancel="showPicker = false"
                @confirm="onConfirm"
            />
        </van-popup>
    </div>
</template>

<!-- 脚本文件 -->

<!-- 样式文件 -->
<style lang="less" scoped>
.tab-page {
    background: url("@/assets/images/index_bg.png") #F3F6FB no-repeat top center;
    background-size: contain;
}

.notice-swipe {
    height: 32px;
    line-height: 32px;
}

.my-swipe {
    img {
        height: 108px;
        border-radius: 10px;
    }
}

.my-swipe .van-swipe-item {
    color: #fff;
    width: 100%;
    line-height: 108px;
    text-align: center;
}

.icon-arrow-right {
    width: 5px;
    height: 7px;
}

.icon-gold {
    width: 63px;
    height: 72px;
}

.myquanbox {
    display: flex;
    gap: 10px;
    // grid-template-columns: 1fr 1fr;
    // grid-gap: 5px;

    .sign-in-item {
        padding: 23px 12px;
        background: #ffffff;
        flex: 1;
    }
}

.menubox {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-gap: 5px;
    padding: 35px 24px;
}
</style>
